package org.erepublik.company.service;

import java.util.ArrayList;
import java.util.Arrays;

import org.erepublik.company.ECountry;
import org.erepublik.company.EProductType;
import org.erepublik.company.comparators.ProductComparatorByPriceInGold;
import org.erepublik.company.product.Raw;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONRawService extends JSONProductService<Raw> {

    public JSONRawService() {
        super("raw");
    }

    @Override
    protected Raw[] getEmptyTable() {
        return new Raw[0];
    }

    @Override
    protected Raw[] getProductFromJSONArray(JSONArray jsonArrayWithFood) throws JSONException {
        Raw[] raws = new Raw[jsonArrayWithFood.length()];
        for (int i = 0; i < jsonArrayWithFood.length(); i++) {
            raws[i] = Raw.getRawFromJSON( (JSONObject)jsonArrayWithFood.get(i) );
        }
        Arrays.sort(raws, new ProductComparatorByPriceInGold());
        return raws;
    }

    


    public Raw[] getRaws(ECountry country, EProductType productType) {
        update();
        if (country==null)
            return filter(allProducts, productType);
        return filter(productMap.get(country), productType);
    }

    
    private Raw[] filter(Raw[] allProducts, EProductType productType) {
        if (productType == null)
            return allProducts;
        ArrayList<Raw> raws = new ArrayList<Raw>();
        for (Raw raw : allProducts) {
            if (raw.getProductType() == productType)
                raws.add(raw);
        }
        return raws.toArray(new Raw[0]);
    }

    
}
